<template>
  <UserLayout :active-index="'3'" :active-menu="'agent-status'">
    <div class="agent-status-content">
      <div class="status-header">
        <h2>中介申请状态</h2>
        <p>查看您的中介申请审核进度和结果</p>
        <div class="header-actions">
          <el-button type="primary" @click="refreshStatus" class="refresh-btn">
            <el-icon><Refresh /></el-icon>
            刷新状态
          </el-button>
          <el-button v-if="applicationStatus.status === 'rejected'" type="danger" @click="confirmResetApplication" class="reset-btn">
            <el-icon><Delete /></el-icon>
            重新申请
          </el-button>
        </div>
      </div>

      <div class="status-content">
        <!-- 没有申请记录时显示 -->
        <div v-if="applicationStatus.status === 'no_application'" class="no-application">
          <el-empty description="您还没有提交中介申请">
            <el-button type="primary" @click="goToApply">立即申请</el-button>
          </el-empty>
        </div>

        <!-- 有申请记录时显示 -->
        <template v-else>
          <!-- 申请状态卡片 -->
          <div class="status-card">
            <div class="status-header">
              <h2>申请信息</h2>
              <el-tag :type="getStatusType(applicationStatus.status)">
                {{ getStatusText(applicationStatus.status) }}
              </el-tag>
            </div>
            <div class="status-details">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="申请编号">{{ applicationStatus.id }}</el-descriptions-item>
                <el-descriptions-item label="申请时间">{{ applicationStatus.applyTime }}</el-descriptions-item>
                <el-descriptions-item label="申请人">{{ applicationStatus.applicant }}</el-descriptions-item>
                <el-descriptions-item label="公司名称">{{ applicationStatus.companyName }}</el-descriptions-item>
                <el-descriptions-item label="联系电话">{{ applicationStatus.phone }}</el-descriptions-item>
                <el-descriptions-item label="申请城市">{{ applicationStatus.city }}</el-descriptions-item>
                <el-descriptions-item label="工作年限">{{ applicationStatus.workYears }}年</el-descriptions-item>
                <el-descriptions-item label="营业执照编号">{{ applicationStatus.licenseNo || '未填写' }}</el-descriptions-item>
                <el-descriptions-item label="审核人员">{{ applicationStatus.auditor || '未分配' }}</el-descriptions-item>
                <el-descriptions-item label="审核时间">{{ applicationStatus.auditTime || '未审核' }}</el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 营业执照图片 -->
            <div v-if="applicationStatus.licensePicPath" class="license-image-section">
              <h3>营业执照</h3>
              <div class="license-image-container">
                <el-image
                    :src="applicationStatus.licensePicPath"
                    :preview-src-list="[applicationStatus.licensePicPath]"
                    fit="contain"
                    class="license-image"
                    :preview-teleported="true"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><Picture /></el-icon>
                      <span>图片加载失败</span>
                    </div>
                  </template>
                </el-image>
                <p class="image-tip">点击图片可放大查看</p>
              </div>
            </div>
          </div>

          <!-- 审核进度 -->
          <div class="status-card">
            <div class="status-header">
              <h2>审核进度</h2>
            </div>
            <el-steps :active="getStepActive(applicationStatus.status)" finish-status="success" align-center>
              <el-step title="提交申请" :description="applicationStatus.applyTime" />
              <el-step title="管理员审核" :description="applicationStatus.reviewTime || (applicationStatus.status === 'pending' ? '等待审核' : '审核中')" />
              <el-step title="审核完成" :description="applicationStatus.auditTime || '待完成'" />
            </el-steps>
          </div>

          <!-- 审核详情 -->
          <div class="status-card">
            <div class="status-header">
              <h2>审核详情</h2>
            </div>
            <div class="audit-details">
              <el-timeline>
                <el-timeline-item
                    v-for="(activity, index) in auditActivities"
                    :key="index"
                    :timestamp="activity.timestamp"
                    :type="activity.type"
                    :hollow="activity.hollow"
                    placement="top"
                >
                  <el-card>
                    <h4>{{ activity.title }}</h4>
                    <p>{{ activity.content }}</p>
                    <p v-if="activity.remark" class="remark">{{ activity.remark }}</p>
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="status-actions">
            <el-button v-if="applicationStatus.status === 'rejected'" type="primary" @click="reapply">
              重新申请
            </el-button>
            <el-button v-if="applicationStatus.status === 'approved'" type="success" @click="goToAgentDashboard">
              进入中介工作台
            </el-button>
            <el-button @click="contactSupport">
              联系客服
            </el-button>
          </div>
        </template>
      </div>
    </div>
  </UserLayout>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import UserLayout from '@/components/layout/UserLayout.vue'
import { Refresh, Bell, Delete, Picture } from '@element-plus/icons-vue'
import api from '@/utils/api'
import { getToken } from '@/utils/auth'

const router = useRouter()

// 初始化申请状态
const initApplicationStatus = () => {
  const savedStatus = localStorage.getItem('agentApplicationStatus')
  if (savedStatus) {
    const status = JSON.parse(savedStatus)
    return {
      id: status.applicationId,
      status: status.status, // pending, reviewing, approved, rejected
      applyTime: new Date(status.submitTime).toLocaleString(),
      applicant: status.applicantName,
      companyName: status.companyName,
      phone: '138****8888', // 隐私保护
      city: '北京市',
      workYears: 5,
      auditor: status.status === 'pending' ? '未分配' : '系统审核员',
      reviewTime: status.status === 'pending' ? '' : '2025-08-02 09:15:30',
      interviewTime: '',
      auditTime: status.status === 'approved' ? '2025-08-03 16:30:00' : ''
    }
  } else {
    // 如果没有申请记录，返回默认状态
    return {
      id: '暂无申请',
      status: 'no_application',
      applyTime: '',
      applicant: '',
      companyName: '',
      phone: '',
      city: '',
      workYears: 0,
      auditor: '',
      reviewTime: '',
      interviewTime: '',
      auditTime: ''
    }
  }
}

const applicationStatus = ref(initApplicationStatus())

// 根据申请状态生成审核活动
const generateAuditActivities = (status, submitTime, refuseReason = '') => {
  const activities = []

  if (status !== 'no_application') {
    activities.push({
      timestamp: submitTime,
      title: '提交申请',
      content: '您已成功提交中介申请',
      type: 'success',
      hollow: false
    })

    if (status === 'pending') {
      activities.push({
        timestamp: '',
        title: '等待审核',
        content: '您的申请正在等待审核员处理',
        remark: '我们将在7个工作日内完成审核，请耐心等待',
        type: 'warning',
        hollow: true
      })
    }

    if (status === 'reviewing') {
      activities.push({
        timestamp: new Date().toLocaleString(),
        title: '资料审核',
        content: '审核员已开始审核您的申请资料',
        type: 'primary',
        hollow: false
      })
    }

    if (status === 'approved') {
      activities.push({
        timestamp: applicationStatus.value?.auditTime || new Date().toLocaleString(),
        title: '审核通过',
        content: '恭喜！您的中介申请已通过审核',
        remark: '您现在可以开始使用中介功能',
        type: 'success',
        hollow: false
      })
    }

    if (status === 'rejected') {
      activities.push({
        timestamp: applicationStatus.value?.auditTime || new Date().toLocaleString(),
        title: '审核拒绝',
        content: '很抱歉，您的申请未通过审核',
        remark: refuseReason || '请检查申请资料后重新提交',
        type: 'danger',
        hollow: false
      })
    }
  }

  return activities
}

const auditActivities = ref(generateAuditActivities(
    applicationStatus.value.status,
    applicationStatus.value.applyTime
))

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待审核',
    submitted: '已提交',
    reviewing: '审核中',
    interview_scheduled: '面试安排',
    approved: '审核通过',
    rejected: '审核拒绝',
    no_application: '暂无申请'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    pending: 'warning',
    submitted: 'info',
    reviewing: 'warning',
    interview_scheduled: 'primary',
    approved: 'success',
    rejected: 'danger',
    no_application: 'info'
  }
  return typeMap[status] || 'info'
}

// 获取步骤激活状态
const getStepActive = (status) => {
  const stepMap = {
    pending: 1,        // 审核中
    submitted: 0,      // 已提交
    reviewing: 1,      // 审核中
    approved: 2,       // 审核完成
    rejected: 1,       // 拒绝时停留在审核步骤
    no_application: -1
  }
  return stepMap[status] || 0
}

// 刷新状态
const refreshStatus = async () => {
  try {
    console.log('正在获取申请状态...')
    // 从后端获取申请状态
    const response = await api.get('/agent/auth/result', {
      headers: {
        'info': getToken()
      }
    })

    console.log('申请状态响应:', response)

    // 处理后端响应
    if (response.data && response.data.code === 200 && response.data.data) {
      const data = response.data.data
      console.log('申请数据:', data)

      // 使用verifyStatus字段
      const statusValue = data.verifyStatus
      console.log('状态字段值:', statusValue)

      applicationStatus.value = {
        status: getStatusFromCertifyStatus(statusValue),
        id: data.agentVerifyId || data.id || `A${Date.now()}`,
        applyTime: formatDate(data.applyTime || data.createTime), // 优先使用applyTime字段
        applicant: data.realName,
        companyName: data.companyName,
        phone: data.phone || '***',
        city: data.city || '未填写',
        workYears: data.workYears || 0,
        licenseNo: data.licenseNo || data.businessLicenseNo || '未填写', // 营业执照编号
        licensePicPath: data.licensePicPath || data.businessLicensePath || '', // 营业执照图片路径
        auditor: data.auditor || '系统审核',
        auditTime: data.auditTime ? formatDate(data.auditTime) : '未审核',
        refuseReason: data.refuseReason || '',
        certifyStatus: statusValue // 保存原始状态值
      }

      console.log('申请时间字段检查:', {
        applyTime: data.applyTime,
        createTime: data.createTime,
        formatted: formatDate(data.applyTime || data.createTime)
      })

      console.log('处理后的申请状态:', applicationStatus.value)
    } else {
      // 没有申请记录
      console.log('没有找到申请记录，响应:', response)
      applicationStatus.value = {
        status: 'no_application',
        message: '您还没有提交中介申请，请先完成申请流程'
      }
    }

    auditActivities.value = generateAuditActivities(
        applicationStatus.value.status,
        applicationStatus.value.applyTime,
        applicationStatus.value.refuseReason
    )

    if (applicationStatus.value.status !== 'no_application') {
      ElMessage.success('状态已刷新')
    }
  } catch (error) {
    console.error('获取申请状态失败:', error)
    // 如果是404或者其他错误，也显示暂未申请
    if (error.response?.status === 404 || error.response?.data?.code === 1001) {
      applicationStatus.value = {
        status: 'no_application',
        message: '您还没有提交中介申请，请先完成申请流程'
      }
      auditActivities.value = generateAuditActivities('no_application', null)
      ElMessage.info('暂无申请记录')
    } else {
      ElMessage.error('获取申请状态失败，请稍后重试')
    }
  }
}

// 将后端的verifyStatus转换为前端的status
const getStatusFromCertifyStatus = (verifyStatus) => {
  console.log('转换状态，原始值:', verifyStatus, '类型:', typeof verifyStatus)

  // 处理字符串和数字类型
  const status = parseInt(verifyStatus)
  console.log('转换后的数字:', status)

  const statusMap = {
    1: 'pending',    // 审核中
    2: 'approved',   // 审核通过
    0: 'rejected'    // 审核未通过
  }

  // 如果verifyStatus是undefined、null或者无法转换为有效数字，默认为no_application
  if (verifyStatus === undefined || verifyStatus === null || verifyStatus === 'undefined' || isNaN(status)) {
    console.log('状态值无效，默认为no_application')
    return 'no_application'
  }

  const result = statusMap[status] || 'no_application'
  console.log('最终状态:', result)
  return result
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''

  console.log('格式化日期输入:', dateString, '类型:', typeof dateString)

  try {
    // 处理数据库的 datetime 格式 (YYYY-MM-DD HH:mm:ss)
    let date
    if (typeof dateString === 'string') {
      // 如果是字符串，直接创建Date对象
      date = new Date(dateString)
    } else {
      // 如果已经是Date对象或时间戳
      date = new Date(dateString)
    }

    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      console.error('无效的日期格式:', dateString)
      return '日期格式错误'
    }

    const formatted = date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })

    console.log('格式化结果:', formatted)
    return formatted
  } catch (error) {
    console.error('日期格式化错误:', error, '原始值:', dateString)
    return '日期解析失败'
  }
}

// 跳转到申请页面
const goToApply = () => {
  router.push('/agent/apply')
}

// 重新申请
const reapply = () => {
  if (applicationStatus.value.status === 'rejected') {
    // 清除之前的申请状态
    localStorage.removeItem('agentApplicationStatus')
    ElMessage.info('正在跳转到申请页面...')
    router.push('/agent/apply')
  } else {
    ElMessage.warning('只有审核被拒绝后才能重新申请')
  }
}

// 进入中介工作台
const goToAgentDashboard = () => {
  ElMessage.info('跳转到中介工作台')
  // 实际项目中应跳转到中介工作台
}

// 联系客服
const contactSupport = () => {
  ElMessage.info('打开客服对话框')
  // 实际项目中应打开客服对话框
}

// 确认重新申请
const confirmResetApplication = () => {
  ElMessageBox.confirm(
      '重新申请将清除当前申请记录，您确定要继续吗？',
      '确认重新申请',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    resetApplication()
  }).catch(() => {
    ElMessage.info('已取消重新申请')
  })
}

// 重新申请（后端会自动软删除之前的记录）
const resetApplication = async () => {
  try {
    // 后端在用户重新申请时会自动软删除之前被拒绝的记录
    // 这里直接跳转到申请页面即可
    ElMessage.success('即将跳转到申请页面，您可以重新提交申请')

    // 跳转到申请页面
    setTimeout(() => {
      router.push('/agent/apply')
    }, 1000)
  } catch (error) {
    console.error('重新申请失败:', error)
    ElMessage.error('重新申请失败，请稍后重试')
  }
}

// 页面加载时获取申请状态
onMounted(() => {
  refreshStatus()
})
</script>

<style scoped>
.agent-status-content {
  height: 100%;
  overflow-y: auto;
}

.agent-status-content::-webkit-scrollbar {
  width: 8px;
}

.agent-status-content::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

.agent-status-content::-webkit-scrollbar-thumb {
  background: rgba(74, 144, 226, 0.6);
  border-radius: 4px;
}

.agent-status-content::-webkit-scrollbar-thumb:hover {
  background: rgba(74, 144, 226, 0.8);
}

.status-header {
  text-align: center;
  margin-bottom: 30px;
  position: relative;
}

.status-header h2 {
  color: #2c3e50;
  font-size: 28px;
  font-weight: 700;
  margin: 0 0 10px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.status-header p {
  color: #7f8c8d;
  font-size: 16px;
  margin: 0 0 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.refresh-btn, .reset-btn {
  border-radius: 20px;
  padding: 10px 20px;
}

.status-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.status-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 15px;
  padding: 25px;
  box-shadow: 0 8px 32px rgba(74, 144, 226, 0.15);
  border: 1px solid rgba(74, 144, 226, 0.2);
  backdrop-filter: blur(10px);
}

.status-card .status-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.status-card .status-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 20px;
  font-weight: 600;
}

.status-details {
  margin-top: 20px;
}

.audit-details {
  margin-top: 20px;
}

.remark {
  color: #f56c6c;
  font-size: 14px;
  margin-top: 10px;
}

.status-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
  padding: 20px 0;
}

/* 营业执照图片样式 */
.license-image-section {
  margin-top: 20px;
}

.license-image-section h3 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.license-image-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border: 1px dashed #dcdfe6;
  border-radius: 8px;
  background-color: #fafafa;
}

.license-image {
  max-width: 400px;
  max-height: 300px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s;
}

.license-image:hover {
  transform: scale(1.02);
}

.image-tip {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 200px;
  height: 150px;
  color: #c0c4cc;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.image-error .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

@media (max-width: 768px) {
  .status-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .status-actions {
    flex-direction: column;
  }

  .status-card .status-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
}
</style>
